package model

import (
	"strings"
	"sync"

	Log "github.com/cihub/seelog"
)

type GlobalVariable struct{}

var (
	globalVariable_AddWg      sync.WaitGroup                 //同步原语,要保证所有的添加都已经完成
	globalVariable_CheckWrite sync.Mutex                     //保存锁
	globalVariable            = make(map[string]interface{}) //注册的全局变量集合
)

// 注册全局变量
func (gv GlobalVariable) RegisterVariable(name string, data interface{}) interface{} {
	globalVariable_AddWg.Add(1)       // 增加计数器
	defer globalVariable_AddWg.Done() // 结束时减少计数器

	globalVariable_CheckWrite.Lock()         //加锁
	defer globalVariable_CheckWrite.Unlock() //解锁

	_, ok := globalVariable[name]
	if ok {
		Log.Error("全局变量重复:" + name)
		return data
	}

	globalVariable[name] = data

	return data
}

// 取指定全局变量
func (gv GlobalVariable) Get(name string) interface{} {
	globalVariable_AddWg.Wait() // 等待所有变量添加完毕

	name = strings.TrimSpace(name)
	if "" == name {
		return nil
	}

	result, ok := globalVariable[name]
	if !ok {
		return nil
	}

	return result
}

// 删除指定全局变量
func (gv GlobalVariable) Del(name string) bool {
	globalVariable_AddWg.Add(1)       // 增加计数器
	defer globalVariable_AddWg.Done() // 结束时减少计数器

	globalVariable_CheckWrite.Lock()         //加锁
	defer globalVariable_CheckWrite.Unlock() //解锁

	name = strings.TrimSpace(name)
	if "" == name {
		return false
	}

	_, ok := globalVariable[name]
	if !ok {
		return true
	}

	delete(globalVariable, name)

	_, ok = globalVariable[name]
	if !ok {
		return true
	}

	return false
}
